package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//用户访问界面
@RestController
@Slf4j
public class UserController {
	//session
	@Autowired
	private HttpSession httpSession;
	//短信验证码模块
	@Autowired
	private SmsTemplate smsTemplate;
	//用户业务
	@Autowired
	private UserService userService;
	@Autowired
	private RedisTemplate redisTemplate;
	//发送短信验证码
	@PostMapping("/user/sendMsg")
	public ResultInfo sendMsg(@RequestBody Map<String, String> map) {
		//接收参数
		String phone = map.get("phone");
		
		//生成验证码
		
		// String code = RandomUtil.randomNumbers(6);
		// todo 测试环境验证码暂时固定
		String code = "123";
		log.info("生成的验证码为{}",code);
		
		//将验证码保存到session
		// httpSession.setAttribute("SMS_" + phone, code);
		
		//将验证码保存到redis中
		redisTemplate.opsForValue().set("SMS_"+phone,code,5, TimeUnit.MINUTES);
		
		
		//发送验证码到手机
		// smsTemplate.sendSms(phone,code);
		
		return ResultInfo.success(null);
	}
	
	@PostMapping("/user/login")
	public ResultInfo login(
			@RequestBody Map<String, String> map
	) {
		String phone = map.get("phone");
		String code = map.get("code");
		
		// 对验证码进行检验
		// String codeFromSession = (String) httpSession.getAttribute("SMS_" + phone);
		
		String codeFromSession = (String) redisTemplate.opsForValue().get("SMS_" + phone);
		if (!StringUtils.equals(code, codeFromSession)
				|| StringUtils.isEmpty(code)
				|| StringUtils.isEmpty(codeFromSession)) {
			return ResultInfo.error("验证码不正确");
		}
		//根据phone 从数据库查询
		User user = userService.findByPhone(phone);
		
		if (user != null){
			//数据表中有用户,是已经注册过的用户
		}else {
			//没有查到,是新用户,登录
			user = new User();
			//设置电话号
			user.setPhone(phone);
			
			//激活
			user.setStatus(1);
			
			userService.save(user);
		}
		
		//将user信息保存到session中
		//代表已经登录
		httpSession.setAttribute("SESSION_USER",user);
		
		return ResultInfo.success(user);
	}
	
	@PostMapping("/user/logout")
	public ResultInfo logout() {
		UserHolder.remove();
		httpSession.invalidate();
		return ResultInfo.success(null);
	}
	
	
	
}
